'use strict';

const jwt = require('jsonwebtoken');

module.exports = function (options) {
  return function jwtAuth(req, res, next) {
    // 跳过不需要认证的路径
    const publicPaths = [
      '/api/Users/login',
      '/api/Users/register',
      '/explorer',
    ];

    if (publicPaths.some(path => req.path.startsWith(path))) {
      return next();
    }

    // 从查询参数或 Authorization 头获取 token
    let token = req.query.access_token || req.headers.authorization;

    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
      token = req.headers.authorization.slice(7);
    }

    if (!token) {
      return next(); // 让 LoopBack 的 ACL 处理未认证的请求
    }

    try {
      // 验证 JWT token
      const decoded = jwt.verify(token, 'your-jwt-secret');

      // 查找用户
      const User = req.app.models.User;
      User.findById(decoded.id, function (err, user) {
        if (err || !user) {
          return res.status(401).json({ error: '无效的 token' });
        }

        // 将用户信息附加到请求对象
        req.accessToken = {
          id: token,
          userId: user.id
        };
        req.user = user;

        // 检查用户是否是管理员
        const Role = req.app.models.Role;
        const RoleMapping = req.app.models.RoleMapping;

        RoleMapping.findOne({
          where: {
            principalType: 'USER',
            principalId: user.id
          },
          include: 'role'
        }, function (err, roleMapping) {
          if (err) {
            return next(err);
          }

          // 设置用户角色信息
          req.user.isAdmin = false;
          if (roleMapping && roleMapping.role && roleMapping.role.name === 'admin') {
            req.user.isAdmin = true;
          }

          next();
        });
      });
    } catch (err) {
      return res.status(401).json({ error: '无效的 token' });
    }
  };
};
